﻿using PLC.Interface.BaseUsers;
using PLCWpfTest.Common;
using PLCWpfTest.Common.Extensions;
using System.Threading.Tasks;
using System.Windows;
using YWM.Dto;

namespace PLCWpfTest.ViewModels
{
    public class UserManagementViewModel : ManagementViewModel
    {
        private readonly IBaseUserAppService _baseUserAppService;

        public BaseUserResultRequestDto Query { get; set; }

        private PagedResultDto<BaseUserResultDto> _baseUserPaged;
        public PagedResultDto<BaseUserResultDto> BaseUserPaged
        {
            get { return _baseUserPaged; }
            set { SetProperty(ref _baseUserPaged, value); }
        }

        public UserManagementViewModel(IBaseUserAppService baseUserAppService)
        {
            _baseUserAppService = baseUserAppService;
            Query = new BaseUserResultRequestDto();
        }

        protected override async Task LoadCommand_Executing(object parameter)
        {
            if (parameter != null)
            {
                Current = 1;
            }
            await SearchAsync();
        }

        public async Task SearchAsync()
        {
            Query.SkipCount = (Current - 1) * Query.MaxResultCount;
            BaseUserPaged = await _baseUserAppService.GetAll(Query);
        }

        protected override bool DeleteCommand_BeforeExecute(object parameter)
        {
            if (parameter == null)
            {
                this.ShowWarning("请选择一行删除");
                return false;
            }
            BaseUserResultDto baseUser = (BaseUserResultDto)parameter;
            if (baseUser.Account.Equals(Constant.ADMIN))
            {
                this.ShowWarning("不能删除超级管理员");
                return false;
            }
            MessageBoxResult result = this.ShowQuestion(Lang["确定要删除吗"]);
            return result == MessageBoxResult.OK;
        }

        protected override async Task<IEntityDto> DeleteAsync(object parameter)
        {
            BaseUserResultDto baseUser = (BaseUserResultDto)parameter;
            await _baseUserAppService.Delete(baseUser);
            await SearchAsync();
            return baseUser;
        }
    }
}
